<template>
  <div class="blind-search">
    <div class="top-box">
      <div class="top-box-child">
        <el-form :model="form" label-width="80px" inline>
          <el-form-item label="选择街道">
            <el-select
              v-model="form.street_id"
              placeholder="请选择街道"
              @change="handleStreetChange"
            >
              <el-option :label="'全区'" :value="0" />
              <el-option
                v-for="item in stationList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <!--el-form-item label="指定站点">
            <el-input
              v-model="form.name"
              placeholder="请输入站点名称"
              clearable
            />
          </el-form-item-->
          <el-form-item>
            <el-button type="primary" @click="handleSearch">确定</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="top-box-child">
        <el-form :model="form" label-width="110px" inline>
          <el-form-item label="选择盲区范围">
            <div style="width: 300px; margin-left: 12px">
              <el-slider
                v-model="form.range"
                :max="3000"
                :marks="marks"
                @change="handleSliderChange"
              />
            </div>
            <el-input
              v-model="form.range1"
              type="number"
              style="width: 120px; margin-left: 24px"
              placeholder="输入范围(米)"
              @input="handleInputChange"
              :min="0"
              :max="1000"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuanSearch">确定</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div class="map-box" id="mapBox"></div>
  </div>
</template>
<script setup>
import { onMounted, ref, watch } from "vue";
import { configList } from "@/api/index.js";
import { garbageStationsList } from "@/api/garbage_stations";
import { publicToiletsList } from "@/api/public_toilets";
import { recyclableSitesList } from "@/api/recyclable_sites";
import { sanitationRoomsList } from "@/api/sanitation_rooms";
import { parkingLotsList } from "@/api/parking_lots";
import { useRoute } from "vue-router";
import { streetsList, operatorsList } from "@/api/index.js";
import { useAppStore } from "@/stores/app.js";
const route = useRoute();
const appStore = useAppStore();

console.log(route, "route");
defineOptions({
  name: "BlindSearch",
});

let map;
const form = ref({
  street_id: 0,
  name: null,
  range: 300,
  range1: 300,
});
const configListData = ref([]);
const ListData = ref([]);
const routeType = ref(null); // 1 公共厕所 2 垃圾压缩站 3 可回收物点站场 4 环卫道班房
const marks = ref({
  0: "0",
  500: "500",
  1000: "1000",
  1500: "1500",
  2000: "2000",
  2500: "2500",
  3000: "3000",
});
const stationList = ref([]);

watch(
  () => route.query,
  (newVal) => {
    if (routeType.value !== newVal.type) {
      // 在这里切换不同的表格或者重新查询数据等
    }
    routeType.value = newVal.type;
    console.log(routeType.value, "routeType.value");
    configList({ pageSize: 20, page: 1 }).then((res) => {
      if (res.code == 0) {
        configListData.value = res.data || [];
        if (routeType.value == 1) {
          getPublicToiletsList();
        } else if (routeType.value == 2) {
          getSanitationRoomsList();
        } else if (routeType.value == 3) {
          getRecyclableSitesList();
        } else if (routeType.value == 4) {
          getSanitationRoomsList();
        } else if (routeType.value == 5) {
          getParkingLotsList();
        }
      }
    });
  },
  {
    immediate: true,
    deep: true,
  }
);

// 处理滑块变化
const handleSliderChange = (value) => {
  form.value.range1 = value;
};

// 处理输入框变化
const handleInputChange = (value) => {
  const numValue = parseInt(value) || 0;
  // 限制输入范围
  if (numValue < 0) {
    form.value.range1 = 0;
    form.value.range = 0;
  } else if (numValue > 1000) {
    form.value.range1 = 1000;
    form.value.range = 1000;
  } else {
    form.value.range = numValue;
  }
};

const handleSearch = () => {
  console.log(form.value);

  if (routeType.value == 1) {
    getPublicToiletsList();
  } else if (routeType.value == 2) {
    getSanitationRoomsList();
  } else if (routeType.value == 3) {
    getRecyclableSitesList();
  } else if (routeType.value == 4) {
    getSanitationRoomsList();
  } else if (routeType.value == 5) {
    getParkingLotsList();
  }
};

const handleQuanSearch = () => {
  console.log(form.value);
  map.clearOverlays();

  let list = ListData.value;
  for (var i = 0; i < list.length; i++) {
    // 使用立即执行函数创建闭包，避免循环变量引用问题
    (function(item, index) {
      // 创建当前标记的坐标点
      const currentPoint = new BMapGL.Point(item.longitude, item.latitude);
      
      // 创建带数字的自定义标记
      var label = new BMapGL.Label("", {
        position: currentPoint,
        offset: new BMapGL.Size(-15, -33),
      });
      
      // 设置标签样式
      label.setStyle({
        backgroundImage: `url('/src/assets/images/map/${item.map_image}')`,
        backgroundSize: "30px 46px",
        backgroundRepeat: "no-repeat",
        backgroundPosition: "center",
        width: "30px",
        height: "46px",
        border: "none",
        fontSize: "14px",
        fontWeight: "bold",
        color: "white",
        textAlign: "center",
        lineHeight: "34px",
        cursor: "pointer",
      });

      // 设置标签内容（数字）
      label.setContent((index + 1).toString());

      // 创建圆
      var circle = new BMapGL.Circle(
        currentPoint,
        form.value.range,
        {
          strokeColor: item.map_border,
          strokeWeight: 2,
          strokeOpacity: 1,
        }
      );

      map.addOverlay(label); // 增加带数字的标记
      map.addOverlay(circle); // 增加圆

      // 创建信息窗口内容
      var opts = {
        width: 250,
        height: 8,
        offset: new BMapGL.Size(0, -30) // 向上偏移，避免被标记遮挡
      };
      var infoContent = `<div style="padding: 5px;font-size:18px;">${item.name}</div>`;
      var infoWindow = new BMapGL.InfoWindow(infoContent, opts);
      
      // 添加点击事件，使用闭包中的currentPoint
      label.addEventListener('click', function () {
        map.openInfoWindow(infoWindow, currentPoint);
      });
    })(list[i], i);
  }
};

onMounted(() => {
  streetsList({}).then((res) => {
    if (res.code == 0) {
      stationList.value = res.data || [];
    }
  });
});

const getGarbageStationsList = () => {
  garbageStationsList({
    is_not_limit: 1,
    is_map: 1,
    street_id: form.value.street_id,
    name: form.value.name,
  }).then((res) => {
    if (res.code == 0) {
      ListData.value = res.data || [];
      map_init();
    }
  });
};

const getRecyclableSitesList = () => {
  recyclableSitesList({
    is_not_limit: 1,
    is_map: 1,
    street_id: form.value.street_id,
    name: form.value.name,
  }).then((res) => {
    if (res.code == 0) {
      ListData.value = res.data || [];
      map_init();
    }
  });
};

const getPublicToiletsList = () => {
  publicToiletsList({
    is_not_limit: 1,
    is_map: 1,
    street_id: form.value.street_id,
    name: form.value.name,
  }).then((res) => {
    if (res.code == 0) {
      ListData.value = res.data || [];
      map_init();
    }
  });
};

const getSanitationRoomsList = () => {
  sanitationRoomsList({
    is_not_limit: 1,
    is_map: 1,
    street_id: form.value.street_id,
    name: form.value.name,
  }).then((res) => {
    if (res.code == 0) {
      ListData.value = res.data || [];
      map_init();
    }
  });
};

const getParkingLotsList = () => {
  parkingLotsList({
    is_not_limit: 1,
    is_map: 1,
    street_id: form.value.street_id,
    name: form.value.name,
  }).then((res) => {
    if (res.code == 0) {
      ListData.value = res.data || [];
      map_init();
    }
  });
};

const map_init = () => {
  map = new BMapGL.Map("mapBox");
  var point = new BMapGL.Point(
    configListData.value[0].map_center_longitude,
    configListData.value[0].map_center_latitude
  );
  map.centerAndZoom(point, configListData.value[0].map_default_zoom);
  map.enableScrollWheelZoom(true);
  map.clearOverlays();
  var scaleCtrl = new BMapGL.ScaleControl(); // 添加比例尺控件
  map.addControl(scaleCtrl);
  var zoomCtrl = new BMapGL.ZoomControl(); // 添加缩放控件
  map.addControl(zoomCtrl);

  let list = ListData.value;
  for (var i = 0; i < list.length; i++) {
    // 使用立即执行函数创建闭包，避免循环变量引用问题
    (function(item, index) {
      // 创建当前标记的坐标点
      const currentPoint = new BMapGL.Point(item.longitude, item.latitude);
      
      // 创建带数字的自定义标记
      var label = new BMapGL.Label("", {
        position: currentPoint,
        offset: new BMapGL.Size(-15, -33),
      });

      // 设置标签样式
      label.setStyle({
        backgroundImage: `url('/src/assets/images/map/${item.map_image}')`,
        backgroundSize: "30px 46px",
        backgroundRepeat: "no-repeat",
        backgroundPosition: "center",
        width: "30px",
        height: "46px",
        border: "none",
        fontSize: "14px",
        fontWeight: "bold",
        color: "white",
        textAlign: "center",
        lineHeight: "34px",
        cursor: "pointer",
      });

      // 设置标签内容（数字）
      label.setContent((index + 1).toString());

      // 创建圆
      var circle = new BMapGL.Circle(
        currentPoint,
        form.value.range,
        {
          strokeColor: item.map_border,
          strokeWeight: 2,
          strokeOpacity: 1,
        }
      );

      map.addOverlay(label); // 增加带数字的标记
      map.addOverlay(circle); // 增加圆

      // 创建信息窗口内容
      var opts = {
        width: 250,
        height: 8,
        offset: new BMapGL.Size(0, -30) // 向上偏移，避免被标记遮挡
      };
      var infoContent = `<div style="padding: 5px;font-size:18px;">${item.name}</div>`;
      var infoWindow = new BMapGL.InfoWindow(infoContent, opts);
      
      // 添加点击事件，使用闭包中的currentPoint
      label.addEventListener('click', function () {
        map.openInfoWindow(infoWindow, currentPoint);
      });
    })(list[i], i);
  }
};
</script>

<style scoped lang="scss">
:deep(.top-box) {
  .el-input,
  .el-select {
    width: 180px;
  }
}
.blind-search {
  height: 100%;
  display: flex;
  flex-direction: column;
  .top-box {
    padding: 16px;
    display: flex;
    justify-content: center;
    align-items: center;
    .top-box-child {
      width: 50%;
    }
  }
  .map-box {
    flex: 1;
    overflow: hidden;
    background: #ccc;
  }
}

//// 自定义滑块样式
//:deep(.el-slider) {
//  .el-slider__runway {
//    background-color: transparent;
//    border: 1px solid #000000;
//    border-radius: 10px;
//    height: 12px;
//  }
//
//  .el-slider__bar {
//    background-color: #1890ff;
//    border-radius: 10px 0 0 10px;
//    height: 8px;
//    margin-top:2px;
//  }
//
//  .el-slider__button {
//    background-color: #409EFF;
//    border: 2px solid white;
//    width: 20px;
//    height: 20px;
//    border-radius: 50%;
//
//    &:hover {
//      background-color: #409EFF;
//    }
//  }
//
//  .el-slider__marks {
//    .el-slider__marks-text {
//      color: #409EFF;
//      font-size: 12px;
//      font-weight: normal;
//    }
//  }
//}

// 隐藏百度地图底部水印与版权信息
:deep() {
  .map-box .anchorBL img,
  .map-box .BMap_cpyCtrl {
    display: none !important;
  }
  .anchorBL img,
  .BMap_cpyCtrl {
    display: none !important;
  }
}
</style>
